package edu.gyc.book.service;

import edu.gyc.book.dao.BookMapper;
import edu.gyc.book.dao.CategoryMapper;
import edu.gyc.book.model.Book;
import edu.gyc.book.model.Category;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class BookServiceImpl implements BookService{

    @Autowired
    BookMapper bookDao;

    @Override
    public boolean addBook(Book book) {
        Book tmp = bookDao.getBookByIsbn(book.getIsbn());
        if (tmp == null) {
            bookDao.insert(book);
            return true;
        }
        return false;
    }

    @Override
    public boolean updateBook(Book book) {
        Book tmp = bookDao.getBookByIsbn(book.getIsbn());
        if (tmp != null) {
            int n = bookDao.updateByPrimaryKey(book);
            if (n == 1) {
                return true;
            }
        }
        return false;
    }

    @Override
    public boolean deleteBook(Integer id) {
        int n = bookDao.deleteByPrimaryKey(id);
        if (n == 1) {
            return true;
        }else {
            return false;
        }
    }

    @Override
    public List<Book> getAllBooks() {

        return bookDao.getAllBooks();
    }

    @Autowired
    CategoryMapper categoryDao;
    @Override
    public List<Book> getBooksByCid(Integer id) {
        List<Book> books=bookDao.getBooksByCid(id);
        if (books.size() > 0) {
            Category category = categoryDao.selectByPrimaryKey(id);
            for (Book book : books) {
                book.setCategory(category);
            }
        }


        return books ;
    }

    @Override
    public Book getBook(Integer id) {
        return bookDao.selectByPrimaryKey(id);
    }
}
